package com.zt.springcloud.controller;


import cloud.zt.springboot.constant.Constants;
import cloud.zt.springboot.utils.Base64;
import cloud.zt.springboot.utils.IdUtils;
import cloud.zt.springboot.utils.ResultUtils;
import com.zt.springcloud.service.RedisService;
import com.zt.springcloud.utils.VerificationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Description: 验证码
 * -------------------
 * @Author: YangXingfu
 * @Date: 2019/07/24 17:01
 */

@RestController
@Slf4j
public class CaptchaController {

    private static final Integer CAPTCHA_CODE_LEN = 4;

    @Autowired
    private RedisService redisCacheService;

    @GetMapping("/captcha")
    public ResultUtils<?> captcha() {
        String verifyCode = VerificationUtil.generateVerifyCode(CAPTCHA_CODE_LEN);

        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        log.debug("验证码: " + verifyCode);
        // 将验证码存入缓存
        redisCacheService.set(verifyKey, verifyCode, 60*5);

        // 生成图片
        int width = 111;
        int height = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//        ResultUtils result = ResultUtils.success();
        HashMap<String, String> result = new HashMap<>();
        try {
            VerificationUtil.outputImage(width, height, stream, verifyCode);
            result.put("uuid", uuid);
            result.put("img", Base64.encode(stream.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtils.success(result);
    }
}
